package com.cyan.learn;

/**
 * 字符串算法
 */
public class StringTest {

    /**
     * 344丶反转字符串
     * 双指针
     */
    public void reverseString(char[] s) {
        int left = 0;
        int right = s.length - 1;

        while (left < right) {
            char t = s[left];
            s[left] = s[right];
            s[right] = t;

            left++;
            right--;
        }
    }


    /**
     * 541丶反转字符拆Ⅱ
     */
    public String reverseStr(String s, int k) {
        StringBuilder sb = new StringBuilder();

        int len = s.length();
        while (len >= k * 2) {
            char[] chars = s.substring(0, k).toCharArray();
            reverseString(chars);
            sb.append(chars).append(s, k, 2 * k);
            len -= k * 2;
            s = s.substring(2 * k);
        }

        if (len > k) {
            char[] chars = s.substring(0, k).toCharArray();
            reverseString(chars);
            sb.append(chars).append(s.substring(k));
        } else {
            char[] arr = s.substring(0, len).toCharArray();
            reverseString(arr);
            sb.append(arr);
        }

        return sb.toString();
    }

    /**
     * 151丶反转字符串的单词
     */
    public String reverseWords(String s) {
        String[] split = s.split(" ");

        StringBuilder sb = new StringBuilder();
        for (int i = split.length - 1; i >= 0; i--) {
            String trim = split[i].trim();
            if (trim.equals("")) {
                continue;
            }

            sb.append(trim).append(" ");
        }

        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    /**
     * 459丶重复的字符串
     * 移动匹配
     */
    public boolean repeatedSubstringPattern(String s) {
        String newStr = s.substring(1) + s.substring(0, s.length() - 1);
        return newStr.contains(s);
    }
    
}
